<template>
  <PageContainer
    title="通用组件演示"
    description="展示项目中所有通用组件的使用效果和功能"
    :icon="Grid"
    :breadcrumb="breadcrumbs"
    :tags="pageTags"
  >
    <template #actions>
      <el-button @click="resetAllForms">重置演示</el-button>
      <el-button type="primary" @click="showGuideDialog = true">查看文档</el-button>
    </template>

    <!-- 组件分类展示 -->
    <el-row :gutter="20">
      <!-- 左侧导航 -->
      <el-col :span="4">
        <el-card shadow="never" class="nav-card">
          <el-menu 
            v-model="activeSection" 
            class="demo-nav"
            @select="scrollToSection"
          >
            <el-menu-item index="upload">📁 文件上传</el-menu-item>
            <el-menu-item index="interaction">🎭 交互组件</el-menu-item>
            <el-menu-item index="display">📊 数据展示</el-menu-item>
            <el-menu-item index="form">📝 表单组件</el-menu-item>
            <el-menu-item index="data">📋 数据组件</el-menu-item>
            <el-menu-item index="layout">📱 布局组件</el-menu-item>
          </el-menu>
        </el-card>
      </el-col>

      <!-- 右侧内容 -->
      <el-col :span="20">
        <!-- 文件上传组件 -->
        <div id="upload" class="demo-section">
          <h2 class="section-title">📁 文件上传组件</h2>
          
          <el-card class="demo-card">
            <template #header>
              <h3>FileUpload - 通用文件上传</h3>
            </template>
            <div class="demo-content">
              <FileUpload
                v-model="demoFiles"
                :multiple="true"
                :limit="5"
                :max-size="10"
                :drag="true"
                accept=".pdf,.doc,.docx,.txt"
                tip="支持拖拽上传，单个文件不超过10MB"
                business-type="demo"
                @success="onFileSuccess"
                @error="onFileError"
              />
              <div class="demo-result">
                <p>已上传文件: {{ demoFiles.length }} 个</p>
              </div>
            </div>
          </el-card>

          <el-card class="demo-card">
            <template #header>
              <h3>ImageUpload - 图片上传</h3>
            </template>
            <div class="demo-content">
              <ImageUpload
                v-model="demoImages"
                :multiple="true"
                :limit="6"
                :max-size="5"
                :item-size="100"
                placeholder-text="添加图片"
                business-type="demo"
                @success="onImageSuccess"
                @error="onFileError"
                @preview="onImagePreview"
              />
              <div class="demo-result">
                <p>已上传图片: {{ demoImages.length }} 个</p>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 交互组件 -->
        <div id="interaction" class="demo-section">
          <h2 class="section-title">🎭 交互组件</h2>
          
          <el-card class="demo-card">
            <template #header>
              <h3>LoadingButton - 智能加载按钮</h3>
            </template>
            <div class="demo-content">
              <div class="button-group">
                <LoadingButton
                  text="普通提交"
                  type="primary"
                  :auto-loading="true"
                  :loading-duration="2000"
                  @click="handleNormalSubmit"
                />
                <LoadingButton
                  text="确认提交"
                  type="warning"
                  confirm-text="确定要提交这些数据吗？"
                  :auto-loading="true"
                  :loading-duration="1500"
                  @click="handleConfirmSubmit"
                />
                <LoadingButton
                  text="危险操作"
                  type="danger"
                  confirm-text="这是一个危险操作，确定要继续吗？"
                  confirm-type="error"
                  :loading="dangerLoading"
                  @click="handleDangerOperation"
                />
              </div>
            </div>
          </el-card>

          <el-card class="demo-card">
            <template #header>
              <h3>ConfirmDialog - 确认对话框</h3>
            </template>
            <div class="demo-content">
              <div class="button-group">
                <el-button @click="showWarningConfirm">警告确认</el-button>
                <el-button type="danger" @click="showDangerConfirm">危险确认</el-button>
                <el-button type="success" @click="showSuccessConfirm">成功确认</el-button>
                <el-button type="info" @click="showInfoConfirm">信息确认</el-button>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 数据展示组件 -->
        <div id="display" class="demo-section">
          <h2 class="section-title">📊 数据展示组件</h2>
          
          <el-card class="demo-card">
            <template #header>
              <h3>StatusTag - 状态标签</h3>
            </template>
            <div class="demo-content">
              <div class="tag-group">
                <div class="tag-row">
                  <span class="tag-label">预设状态:</span>
                  <StatusTag :status="1" />
                  <StatusTag :status="0" />
                  <StatusTag status="pending" />
                  <StatusTag status="processing" />
                  <StatusTag status="completed" />
                  <StatusTag status="failed" />
                </div>
                <div class="tag-row">
                  <span class="tag-label">自定义状态:</span>
                  <StatusTag 
                    text="VIP用户" 
                    type="warning" 
                    :icon="Star" 
                  />
                  <StatusTag 
                    text="新用户" 
                    type="success" 
                    :icon="User" 
                  />
                </div>
              </div>
            </div>
          </el-card>

          <el-card class="demo-card">
            <template #header>
              <h3>EmptyState - 空状态</h3>
            </template>
            <div class="demo-content">
              <el-row :gutter="20">
                <el-col :span="8">
                  <EmptyState
                    title="暂无数据"
                    description="没有找到相关数据"
                    illustration="no-data"
                    size="small"
                    :show-default-action="true"
                    action-text="刷新"
                    @action="refreshData"
                  />
                </el-col>
                <el-col :span="8">
                  <EmptyState
                    title="没有文件"
                    description="还没有上传任何文件"
                    illustration="no-file"
                    :show-default-action="true"
                    action-text="上传文件"
                    @action="showUpload"
                  />
                </el-col>
                <el-col :span="8">
                  <EmptyState
                    title="网络异常"
                    description="请检查网络连接"
                    illustration="no-network"
                    :show-default-action="true"
                    action-text="重试"
                    @action="retry"
                  />
                </el-col>
              </el-row>
            </div>
          </el-card>
        </div>

        <!-- 表单组件 -->
        <div id="form" class="demo-section">
          <h2 class="section-title">📝 表单组件</h2>
          
          <el-card class="demo-card">
            <template #header>
              <h3>SearchForm - 搜索表单</h3>
            </template>
            <div class="demo-content">
              <SearchForm
                :fields="searchFields"
                layout="inline"
                :max-visible-items="3"
                :auto-search="false"
                @search="handleSearch"
                @reset="handleSearchReset"
              />
              <div class="demo-result">
                <p>搜索结果: {{ JSON.stringify(searchResult, null, 2) }}</p>
              </div>
            </div>
          </el-card>

          <el-card class="demo-card">
            <template #header>
              <h3>FormDialog - 表单对话框</h3>
            </template>
            <div class="demo-content">
              <div class="button-group">
                <el-button type="primary" @click="showUserForm">用户表单</el-button>
                <el-button type="success" @click="showProductForm">产品表单</el-button>
                <el-button @click="showComplexForm">复杂表单</el-button>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 数据组件 -->
        <div id="data" class="demo-section">
          <h2 class="section-title">📋 数据组件</h2>
          
          <el-card class="demo-card">
            <template #header>
              <h3>DataTable - 增强数据表格</h3>
            </template>
            <div class="demo-content">
              <DataTable
                :data="tableData"
                :columns="tableColumns"
                :loading="tableLoading"
                :total="tableTotal"
                :current-page="tablePage"
                :page-size="tableSize"
                :actions="tableActions"
                selectable
                show-index
                @selection-change="handleTableSelection"
                @page-change="handleTablePageChange"
                @action-click="handleTableAction"
              >
                <template #batch-actions="{ selectedRows }">
                  <el-button size="small" type="danger" @click="batchDelete(selectedRows)">
                    批量删除 ({{ selectedRows.length }})
                  </el-button>
                </template>
                
                <template #avatar="{ row }">
                  <el-avatar :size="32">{{ row.name.charAt(0) }}</el-avatar>
                </template>
              </DataTable>
            </div>
          </el-card>
        </div>

        <!-- 布局组件演示已在当前页面中 -->
        <div id="layout" class="demo-section">
          <h2 class="section-title">📱 布局组件</h2>
          
          <el-card class="demo-card">
            <template #header>
              <h3>PageContainer - 页面容器</h3>
            </template>
            <div class="demo-content">
              <p>当前页面就是使用 PageContainer 组件构建的，包含：</p>
              <ul class="feature-list">
                <li>✅ 页面标题和描述</li>
                <li>✅ 面包屑导航</li>
                <li>✅ 页面标签</li>
                <li>✅ 操作按钮区域</li>
                <li>✅ 响应式布局</li>
                <li>✅ 统一的页面结构</li>
              </ul>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>

    <!-- 对话框 -->
    <ConfirmDialog
      v-model="confirmDialog.visible"
      :type="confirmDialog.type"
      :title="confirmDialog.title"
      :message-title="confirmDialog.messageTitle"
      :message="confirmDialog.message"
      :confirm-type="confirmDialog.confirmType"
      :loading="confirmDialog.loading"
      @confirm="confirmDialog.onConfirm"
    />

    <FormDialog
      v-model="formDialog.visible"
      :title="formDialog.title"
      :fields="formDialog.fields"
      :form-data="formDialog.data"
      :submitting="formDialog.submitting"
      :width="formDialog.width"
      @submit="handleFormSubmit"
      @cancel="formDialog.visible = false"
    >
      <template #demo-upload="{ value, setValue }">
        <FileUpload
          :model-value="value"
          @update:model-value="setValue"
          :limit="3"
          business-type="demo"
        />
      </template>
    </FormDialog>

    <!-- 文档对话框 -->
    <el-dialog v-model="showGuideDialog" title="组件使用指南" width="80%" class="guide-dialog">
      <div class="guide-content">
        <p>请查看项目中的 <code>src/components/ComponentsGuide.md</code> 文件，了解详细的组件使用方法。</p>
        
        <h4>快速开始：</h4>
        <ol>
          <li>从 <code>@/components</code> 导入需要的组件</li>
          <li>在模板中使用组件</li>
          <li>配置组件属性和事件</li>
          <li>使用插槽自定义内容</li>
        </ol>

        <h4>组件列表：</h4>
        <ul>
          <li><strong>FileUpload</strong> - 通用文件上传</li>
          <li><strong>ImageUpload</strong> - 图片上传</li>
          <li><strong>ConfirmDialog</strong> - 确认对话框</li>
          <li><strong>LoadingButton</strong> - 智能加载按钮</li>
          <li><strong>StatusTag</strong> - 状态标签</li>
          <li><strong>EmptyState</strong> - 空状态</li>
          <li><strong>SearchForm</strong> - 搜索表单</li>
          <li><strong>FormDialog</strong> - 表单对话框</li>
          <li><strong>DataTable</strong> - 增强数据表格</li>
          <li><strong>PageContainer</strong> - 页面容器</li>
        </ul>
      </div>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { 
  Grid, Star, User, House, Document, 
  CircleCheckFilled, CircleCloseFilled 
} from '@element-plus/icons-vue'
import {
  PageContainer, FileUpload, ImageUpload, LoadingButton,
  ConfirmDialog, StatusTag, EmptyState, SearchForm,
  FormDialog, DataTable
} from '@/components'
import { ElMessage } from 'element-plus'

// 页面配置
const breadcrumbs = [
  { title: '首页', path: '/', icon: House },
  { title: '示例页面', path: '/examples' },
  { title: '组件演示' }
]

const pageTags = [
  { text: '组件库', type: 'primary' },
  { text: '演示', type: 'success' }
]

// 导航状态
const activeSection = ref('upload')

// 上传演示
const demoFiles = ref([])
const demoImages = ref([])

// 按钮演示
const dangerLoading = ref(false)

// 确认对话框
const confirmDialog = reactive({
  visible: false,
  type: 'warning',
  title: '确认操作',
  messageTitle: '确定要执行此操作吗？',
  message: '',
  confirmType: 'primary',
  loading: false,
  onConfirm: () => {}
})

// 表单对话框
const formDialog = reactive({
  visible: false,
  title: '表单',
  fields: [],
  data: {},
  submitting: false,
  width: '600px'
})

// 搜索表单
const searchFields = [
  {
    prop: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '请输入关键词'
  },
  {
    prop: 'category',
    label: '分类',
    type: 'select',
    options: [
      { label: '全部', value: '' },
      { label: '技术', value: 'tech' },
      { label: '产品', value: 'product' },
      { label: '设计', value: 'design' }
    ]
  },
  {
    prop: 'status',
    label: '状态',
    type: 'select',
    options: [
      { label: '全部', value: '' },
      { label: '启用', value: 1 },
      { label: '禁用', value: 0 }
    ]
  },
  {
    prop: 'dateRange',
    label: '时间范围',
    type: 'daterange'
  }
]

const searchResult = ref({})

// 数据表格
const tableLoading = ref(false)
const tableData = ref([])
const tableTotal = ref(50)
const tablePage = ref(1)
const tableSize = ref(10)

const tableColumns = [
  { 
    prop: 'avatar', 
    label: '头像', 
    width: 80, 
    type: 'slot',
    slot: 'avatar'
  },
  { prop: 'name', label: '姓名', width: 120 },
  { prop: 'email', label: '邮箱', minWidth: 180 },
  { 
    prop: 'status', 
    label: '状态', 
    width: 80,
    type: 'status',
    statusMap: {
      1: { text: '启用', type: 'success', icon: CircleCheckFilled },
      0: { text: '禁用', type: 'danger', icon: CircleCloseFilled }
    }
  },
  { 
    prop: 'createTime', 
    label: '创建时间', 
    width: 160,
    type: 'date',
    dateFormat: 'YYYY-MM-DD'
  }
]

const tableActions = [
  {
    key: 'edit',
    text: '编辑',
    type: 'button',
    buttonType: 'primary'
  },
  {
    key: 'delete',
    text: '删除',
    type: 'button',
    buttonType: 'danger'
  }
]

const showGuideDialog = ref(false)

// 事件处理
const scrollToSection = (section: string) => {
  const element = document.getElementById(section)
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' })
  }
}

const onFileSuccess = (file: any, response: any) => {
  ElMessage.success(`文件 ${file.name} 上传成功`)
}

const onImageSuccess = (file: any, response: any) => {
  ElMessage.success(`图片 ${file.name} 上传成功`)
}

const onFileError = (error: any, file: any) => {
  ElMessage.error(`文件 ${file.name} 上传失败`)
}

const onImagePreview = (file: any) => {
  ElMessage.info(`预览图片: ${file.name}`)
}

const handleNormalSubmit = () => {
  ElMessage.success('普通提交完成')
}

const handleConfirmSubmit = () => {
  ElMessage.success('确认提交完成')
}

const handleDangerOperation = () => {
  dangerLoading.value = true
  setTimeout(() => {
    dangerLoading.value = false
    ElMessage.success('危险操作完成')
  }, 2000)
}

const showWarningConfirm = () => {
  confirmDialog.visible = true
  confirmDialog.type = 'warning'
  confirmDialog.messageTitle = '确定要删除这条记录吗？'
  confirmDialog.message = '删除后将无法恢复，请谨慎操作。'
  confirmDialog.confirmType = 'danger'
  confirmDialog.onConfirm = () => {
    confirmDialog.loading = true
    setTimeout(() => {
      confirmDialog.loading = false
      confirmDialog.visible = false
      ElMessage.success('删除成功')
    }, 1000)
  }
}

const showDangerConfirm = () => {
  confirmDialog.visible = true
  confirmDialog.type = 'error'
  confirmDialog.messageTitle = '这是一个危险操作！'
  confirmDialog.message = '此操作将清空所有数据，确定要继续吗？'
  confirmDialog.confirmType = 'danger'
  confirmDialog.onConfirm = () => {
    confirmDialog.visible = false
    ElMessage.warning('操作已取消')
  }
}

const showSuccessConfirm = () => {
  confirmDialog.visible = true
  confirmDialog.type = 'success'
  confirmDialog.messageTitle = '操作成功！'
  confirmDialog.message = '数据已保存，是否继续添加？'
  confirmDialog.confirmType = 'success'
  confirmDialog.onConfirm = () => {
    confirmDialog.visible = false
    ElMessage.success('继续添加')
  }
}

const showInfoConfirm = () => {
  confirmDialog.visible = true
  confirmDialog.type = 'info'
  confirmDialog.messageTitle = '提示信息'
  confirmDialog.message = '系统将在5分钟后进行维护，是否继续当前操作？'
  confirmDialog.confirmType = 'primary'
  confirmDialog.onConfirm = () => {
    confirmDialog.visible = false
    ElMessage.info('继续操作')
  }
}

const handleSearch = (params: any) => {
  searchResult.value = params
  ElMessage.success('搜索完成')
}

const handleSearchReset = () => {
  searchResult.value = {}
  ElMessage.info('搜索条件已重置')
}

const showUserForm = () => {
  formDialog.visible = true
  formDialog.title = '用户信息'
  formDialog.width = '600px'
  formDialog.fields = [
    { prop: 'name', label: '姓名', type: 'input', required: true, span: 12 },
    { prop: 'email', label: '邮箱', type: 'input', inputType: 'email', required: true, span: 12 },
    { prop: 'phone', label: '电话', type: 'input', span: 12 },
    { prop: 'status', label: '状态', type: 'switch', span: 12 },
    { prop: 'description', label: '描述', type: 'textarea', span: 24 }
  ]
  formDialog.data = {}
}

const showProductForm = () => {
  formDialog.visible = true
  formDialog.title = '产品信息'
  formDialog.width = '700px'
  formDialog.fields = [
    { prop: 'name', label: '产品名称', type: 'input', required: true, span: 12 },
    { prop: 'price', label: '价格', type: 'number', min: 0, span: 12 },
    { prop: 'category', label: '分类', type: 'select', options: [
      { label: '电子产品', value: 'electronics' },
      { label: '服装', value: 'clothing' }
    ], span: 12 },
    { prop: 'rating', label: '评分', type: 'rate', span: 12 },
    { prop: 'description', label: '描述', type: 'textarea', span: 24 }
  ]
  formDialog.data = {}
}

const showComplexForm = () => {
  formDialog.visible = true
  formDialog.title = '复杂表单'
  formDialog.width = '800px'
  formDialog.fields = [
    { prop: 'title', label: '标题', type: 'input', required: true, span: 24 },
    { type: 'divider', text: '基本信息' },
    { prop: 'name', label: '姓名', type: 'input', span: 12 },
    { prop: 'email', label: '邮箱', type: 'input', span: 12 },
    { prop: 'startDate', label: '开始日期', type: 'date', span: 12 },
    { prop: 'endDate', label: '结束日期', type: 'date', span: 12 },
    { type: 'divider', text: '文件上传' },
    { prop: 'files', label: '附件', type: 'slot', slotName: 'demo-upload', span: 24 },
    { prop: 'description', label: '说明', type: 'textarea', rows: 4, span: 24 }
  ]
  formDialog.data = {}
}

const handleFormSubmit = (data: any) => {
  formDialog.submitting = true
  setTimeout(() => {
    formDialog.submitting = false
    formDialog.visible = false
    ElMessage.success('表单提交成功')
  }, 1500)
}

const handleTableSelection = (selection: any[]) => {
  console.log('选中行:', selection)
}

const handleTablePageChange = (page: number) => {
  tablePage.value = page
  loadTableData()
}

const handleTableAction = (action: any, row: any, index: number) => {
  if (action.key === 'edit') {
    ElMessage.info(`编辑用户: ${row.name}`)
  } else if (action.key === 'delete') {
    ElMessage.warning(`删除用户: ${row.name}`)
  }
}

const batchDelete = (rows: any[]) => {
  ElMessage.warning(`批量删除 ${rows.length} 条记录`)
}

const refreshData = () => {
  ElMessage.info('刷新数据')
}

const showUpload = () => {
  ElMessage.info('显示上传')
}

const retry = () => {
  ElMessage.info('重试连接')
}

const resetAllForms = () => {
  demoFiles.value = []
  demoImages.value = []
  searchResult.value = {}
  ElMessage.success('所有演示数据已重置')
}

const loadTableData = () => {
  tableLoading.value = true
  setTimeout(() => {
    tableData.value = [
      { 
        id: 1, 
        name: '张三', 
        email: 'zhangsan@example.com', 
        status: 1, 
        createTime: '2024-01-01' 
      },
      { 
        id: 2, 
        name: '李四', 
        email: 'lisi@example.com', 
        status: 0, 
        createTime: '2024-01-02' 
      },
      { 
        id: 3, 
        name: '王五', 
        email: 'wangwu@example.com', 
        status: 1, 
        createTime: '2024-01-03' 
      }
    ]
    tableLoading.value = false
  }, 500)
}

onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
.demo-section {
  margin-bottom: 40px;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.demo-card {
  margin-bottom: 20px;
}

.demo-card :deep(.el-card__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.demo-card h3 {
  margin: 0;
  font-size: 16px;
  color: #495057;
}

.demo-content {
  padding: 20px 0;
}

.demo-result {
  margin-top: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.demo-result p {
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #495057;
}

.button-group {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.tag-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.tag-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.tag-label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.nav-card {
  position: sticky;
  top: 20px;
}

.demo-nav {
  border: none;
}

.demo-nav .el-menu-item {
  height: 40px;
  line-height: 40px;
}

.feature-list {
  margin: 16px 0;
  padding-left: 20px;
}

.feature-list li {
  margin-bottom: 8px;
  color: #606266;
}

.guide-dialog .guide-content {
  line-height: 1.6;
}

.guide-content code {
  background: #f1f3f4;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
}

.guide-content h4 {
  margin-top: 24px;
  margin-bottom: 12px;
  color: #303133;
}

.guide-content ul li,
.guide-content ol li {
  margin-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .demo-section {
    margin-bottom: 30px;
  }
  
  .button-group {
    flex-direction: column;
    align-items: stretch;
  }
  
  .tag-row {
    flex-direction: column;
    align-items: flex-start;
  }
}

@media (max-width: 768px) {
  .section-title {
    font-size: 20px;
  }
  
  .demo-content {
    padding: 12px 0;
  }
  
  .nav-card {
    position: static;
    margin-bottom: 20px;
  }
}
</style>
